<?php

/**
 * @Name  融云IM
 * @Description 融云IM封装工具类
 */

namespace App\Util;

use App\Model\User;
use Illuminate\Support\Facades\Log;

class ImUtil
{
    //融云消息类型
    const RONG_TEXT_TYPE = 'RC:TxtMsg';
    const RONG_IMG_TYPE = 'RC:ImgMsg';
    const RONG_SOUND_TYPE = 'RC:VcMsg';
    const RONG_CMD_TYPE = 'RC:CmdMsg';
    const RONG_HQ_SOUND_TYPE = 'RC:HQVCMsg';
    const RONG_READ_NTF = 'RC:ReadNtf';

    //单聊 - 单次批量发送消息最大数
    const SINGLE_MAX_NUM = 999;
    //消息推送最大
    const PUSH_MESSAGE_NUM = 99;

    /**
     * 发送静默消息
     * @param string $account
     * @param array $msgInfo
     */
    static function sendSilentMsg($account = '', $msgInfo = [])
    {
        $accounts = !is_array($account) ? [$account] : $account;
        $content = json_encode([
            'name' => 'cmd',
            'data' => $msgInfo,
        ]);
        $sender = config('busi.officialImAccount');
        $isIncludeSender = $isCounted = $isPersisted = 0;
        $ret = 0;
        try {
            $ret = (new RongCloud())->messagePrivatePublish(
                $sender,
                $accounts,
                self::RONG_CMD_TYPE,
                $content,
                $isIncludeSender,
                $isCounted,
                $isPersisted
            );
        } catch (\Exception $e) {
            \Log::info(__CLASS__ . "==sendSilentMsg==Exception:" . $e->getMessage());
        }
        \Log::info(__CLASS__ . "==sendSilentMsg==Accounts:" . json_encode($accounts) . "==MsgInfo:" . json_encode($msgInfo) . "==" . json_encode($ret));
        return $ret;
    }

    /**
     * 纯push推送
     * @return mixed
     */
    static function sendPushMsg(
        $receivers = [],
        $content = [],
        $msgType = '',
        $pushContent = ''
    ) {
        $receivers = !is_array($receivers) ? [$receivers] : array_values($receivers);
        $content = json_encode($content);
        $sender = config('busi.officialImAccount');
        $isIncludeSender = $isCounted = $isPersisted = 0;
        $accountArr = array_chunk($receivers, self::SINGLE_MAX_NUM);
        $ret = 0;
        foreach ($accountArr as $k => $accounts) {
            try {
                $ret = (new RongCloud())->messagePrivatePublish(
                    $sender,
                    $accounts,
                    $msgType,
                    $content,
                    $isIncludeSender,   //暂不存储发送方
                    $isCounted, //不显示未读消息
                    $isPersisted,   //融云服务端不存储
                    $pushContent,  //显示的 Push 内容
                    $pushData = $content  //Android客户端收到推送消息字段
                );
                \Log::info(__CLASS__ . "==sendPushMsg==Round:{$k}==" . json_encode($accounts) . "=={$content}=={$ret}");
            } catch (\Exception $e) {
                continue;
            }
        }
        return $ret;
    }

    /**
     * 官方推送 - 全员通知（落地）
     */
    static function officialPushToAll(
        $content = [],
        $msgType = self::RONG_TEXT_TYPE,
        $pushContent = '你有一条新消息~'
    ) {
        //发送消息ID
        $fromUserId = config('busi.officialImAccount');
        $ret = (new RongCloud())->messageBroadcast($fromUserId, $msgType, json_encode($content), $pushContent);
        \Log::info(__CLASS__ . "==officialPushToAll=={$msgType}=={$ret}==" . json_encode($content));
        return $ret;
    }

    /**
     * 官方推送（人工推送，活动、公告这类）
     */
    static function officialPushToSingle(
        $toUsers = [],
        $content = [],
        $msgType = self::RONG_TEXT_TYPE,
        $pushContent = '你有一条新消息~'
    ) {
        //发送消息ID
        $fromUserId = config('busi.officialImAccount');
        $toUsers = array_values($toUsers);
        $accountArr = array_chunk($toUsers, self::PUSH_MESSAGE_NUM);
        $ret = 0;
        foreach ($accountArr as $round => $accounts) {
            $ret = (new RongCloud())->messageSystemPublish($fromUserId, $accounts, $msgType, json_encode($content), $pushContent);
            Log::info(__CLASS__ . "==officialPushToSingle==From:{$fromUserId}==MsgType:{$msgType}==Count:" . count($accounts) . "==" . json_encode($content));
            if (count($accounts) < 10) {
                Log::info(__CLASS__ . "==officialPushToSingle==To:" . json_encode($accounts));
            }
        }
        return $ret;
    }

    /**
     * 系统消息（日常系统审核结果等一些系统自动的消息推送）
     */
    static function systemPushToSingle(
        $toUsers = [],
        $content = [],
        $msgType = self::RONG_TEXT_TYPE,
        $pushContent = '你有一条新消息~'
    ) {
        //发送消息ID
        $fromUserId = config('busi.systemImAccount');
        $toUsers = array_values($toUsers);
        $content = [
            'content' => $content,
            'extra' => $pushContent,
        ];
        $ret = (new RongCloud())->messageSystemPublish($fromUserId, $toUsers, $msgType, json_encode($content), $pushContent);
        \Log::info(__CLASS__ . "==systemPushToSingle=={$msgType}==" . json_encode($toUsers) . "=={$ret}==" . json_encode($content));
        return $ret;
    }

    /**
     * 融云踢下线
     */
    static function kickOut($userIds = [])
    {
        if (empty($userIds)) return false;
        //兼容非数组
        if (!is_array($userIds)) $userIds = [$userIds];
        $accounts = User::getImAccounts($userIds, false);
        return (new RongCloud())->userBlock(array_values($accounts), 43200);
    }

    /**
     * 融云取消封禁
     */
    static function cancelKickOut($userIds = [])
    {
        if (empty($userIds)) return false;
        //兼容非数组
        if (!is_array($userIds)) $userIds = [$userIds];
        $accounts = User::getImAccounts($userIds, false);
        return (new RongCloud())->userUnBlock(array_values($accounts));
    }

    /**
     * 删除黑名单
     * @param string $account
     * @param string $black_account
     */
    public static function delBlackList($account = '', $black_account = '')
    {
        $ret = (new RongCloud())->userBlacklistRemove($account, [$black_account]);

        return $ret;
    }
}
